package com.pospi.pospihold.ui.pay_ui;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.dto.OrderBeen;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.PayBeen;
import com.pospi.pospihold.greendao.PayBeenDao;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.http.UploadData;
import com.pospi.pospihold.print.PrintClient;
import com.pospi.pospihold.print.PrintHelper;
import com.pospi.pospihold.print.UnionPrint;
import com.pospi.pospihold.print.a920.PrintA920;
import com.pospi.pospihold.sprint.StarPrintHelper;
import com.pospi.pospihold.ui.CaptureActivity;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.BlankHelper;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.LoadingDialog;
import com.pospi.pospihold.util.Model;
import com.pospi.pospihold.util.OrderNoUtil;
import com.pospi.pospihold.util.PareseJson;
import com.ums.AppHelper;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.pospi.pospihold.ui.pay_ui.PayActivity.PUT_MAXNO;
import static com.pospi.pospihold.ui.pay_ui.PayActivity.PUT_PAYWAY;
import static com.pospi.pospihold.ui.pay_ui.PayActivity.PUT_SS;
import static com.pospi.pospihold.ui.pay_ui.PayActivity.PUT_YS;
import static com.pospi.pospihold.ui.pay_ui.PayActivity.PUT_ZL;

/**
 * Created by acer on 2018/9/29.
 */

public class PayNewActivity extends AppCompatActivity{
    private static final int REQUEST_CODE = 110;
    @Bind(R.id.je_title)
    TextView je_title;
    @Bind(R.id.je_ss)
    TextView je_ss;
    @Bind(R.id.je_ys)
    TextView je_ys;
    @Bind(R.id.je_zl)
    TextView je_zl;
    @Bind(R.id.bt_pay)
    TextView bt_pay;
    @Bind(R.id.rl_cash)
    RelativeLayout rl_cash;
    @Bind(R.id.rl_ali)
    RelativeLayout rl_ali;
    @Bind(R.id.rl_wx)
    RelativeLayout rl_wx;
    @Bind(R.id.rl_blank)
    RelativeLayout rl_blank;
    @Bind(R.id.rl_integer)
    RelativeLayout rl_integer;
    @Bind(R.id.rl_ohter)
    RelativeLayout rl_other;
    @Bind(R.id.iv_cash)
    ImageView iv_cash;
    @Bind(R.id.iv_ali)
    ImageView iv_ali;
    @Bind(R.id.iv_wx)
    ImageView iv_wx;
    @Bind(R.id.iv_blank)
    ImageView iv_blank;
    @Bind(R.id.iv_integer)
    ImageView iv_integer;
    @Bind(R.id.iv_other)
    ImageView iv_other;
    private ImageView[] payImg;
    private String je;
    private int payCode = 0;
    private String payWayString;
    private PayBeen payBeen;
    private OrderDto orderDto;

    private String goodsInfo;
    private int orderNo;
    private String remark;
    private OrderBeen orderBeen;
    private String unionId = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_pay_new);
        ButterKnife.bind(this);
        payImg = new ImageView[]{iv_cash, iv_ali, iv_wx,
                iv_integer, iv_blank, iv_other};
        je = getIntent().getStringExtra("data");
        remark = getIntent().getStringExtra("remark");
        orderNo = Integer.parseInt(GetData.getYYMMDDNoSpellingTime() + GetData.getHHmmssTime().substring(0,4));

        init();
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PayUtil.SUCCESS:
                    unionId = (String) msg.obj;
                    Log.i("pay", unionId + "----");
                    handleSucess();
                    break;
                case PayUtil.FAILED:
                    closeLoading();
                    Toast.makeText(PayNewActivity.this, "失败：" + msg.obj, Toast.LENGTH_SHORT).show();
//                    new AlertDialog.Builder(PayNewActivity.this)
//                            .setTitle("提示")
//                            .setMessage((String) msg.obj).setPositiveButton("确认",null).show();

                    break;
                case PayUtil.UPSUCCESS://上传成功
                    Log.i("up", "上传成功----" + orderBeen.getOrderNo());
                    break;
                case PayUtil.UPFAILED://上传失败
                    Toast.makeText(PayNewActivity.this, "订单未上传", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void init() {
        for (ImageView img : payImg) {
            img.setVisibility(View.INVISIBLE);
        }
        je_title.setText(je);
        je_ys.setText(je);

    }
    private void handleSucess() {
        getOrder();
        closeLoading();
        upOrder();
        OrderNoUtil.updateNumber();
        new UnionPrint(this).print(orderBeen);
        paySuccess();
    }
    private void setSs(){
       je_ss.setText(je);
    }

    @OnClick({R.id.rl_cash, R.id.rl_ali,
            R.id.rl_wx, R.id.rl_blank,
            R.id.rl_integer, R.id.rl_ohter,
            R.id.bt_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_cash:
                initCheck(iv_cash);
                payCode = Constant.PAYMENT_CASH;
                payWayString = Constant.PAYMENT_CASH_String;
                break;
            case R.id.rl_ali:
                initCheck(iv_ali);
                payCode = Constant.PAYMENT_ALIPAY;
                payWayString = Constant.PAYMENT_ALIPAY_String;
                break;
            case R.id.rl_wx:
                initCheck(iv_wx);
                payCode = Constant.PAYMENT_WEIXIN;
                payWayString = Constant.PAYMENT_WEIXIN_String;
                break;
            case R.id.rl_blank:
                initCheck(iv_blank);
                payCode = Constant.PAYMENT_BANK_CARD;
                payWayString = Constant.PAYMENT_BANK_CARD_String;
                break;
//            case R.id.rl_integer:
//                initCheck(iv_integer);
//                payCode = Constant.PAYMENT_INTEGAL;
//                payWayString = Constant.PAYMENT_INTEGAL_String;
//                break;
//            case R.id.rl_ohter:
//                initCheck(iv_other);
//                payCode = Constant.PAYMENT_OTHER;
//                payWayString = Constant.PAYMENT_OTHER_String;
//                break;
            case R.id.bt_pay:
//                bt_pay.setClickable(false);
                requestPay();
                break;
        }
    }

    private String TAG = "test";
    private void requestPay() {
        if (payCode != 0) {
            payBeen = App.getInstance().getDaoSession().getPayBeenDao().queryBuilder().where(PayBeenDao.Properties.Name.eq(payWayString)).unique();
            switch (payCode) {
                case Constant.PAYMENT_CASH:
                    showLoading("");
                    new PayUtil(handler, je, payCode).startCash();
                    break;
                case Constant.PAYMENT_ALIPAY:
                case Constant.PAYMENT_WEIXIN:
//                    requestScan();
                    BlankHelper.requestScan(this,"1");
                    break;
                case Constant.PAYMENT_BANK_CARD:
//                    Toast.makeText(this, "暂时不支持", Toast.LENGTH_SHORT).show();
//                    showLoading("");
//                    new PayUtil(handler,je,payCode,this).startPayBlank();
                    BlankHelper.request(this,"1");
                    break;
            }



        } else {
            Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
        }
    }

    private static final String packName = "cn.bw.unionpay.demo2";
    private static final String baseDir = "cn.basewin.unionpay.external.";
    private static final String printAty = baseDir + "PrintExternalAty";
    Intent intent;
    private void requestScan() {

        if (PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)) {
            //有访问摄像头的权限
            intent = new Intent(this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问摄像头的权限
                    intent = new Intent(PayNewActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }


                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问摄像头的申请
                }
            }, new String[]{Manifest.permission.CAMERA});
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String code = "";
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            try {
                code = data.getStringExtra("code");
                if (!code.isEmpty()) {
                    showLoading("支付中...");
                    new PayUtil(handler, je, payCode).startAliAndWx(code);
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
                Toast.makeText(this, "二维码解析失败", Toast.LENGTH_SHORT).show();
            }


        }

        if(AppHelper.TRANS_REQUEST_CODE == requestCode){
            Log.d(TAG, "resultCode" + resultCode);
            if (Activity.RESULT_OK == resultCode) {
                if (null != data) {
                    String msg = data.getStringExtra("resultCode");
                    if (msg != null) {
                        if (data.getStringExtra("resultCode").equals("0")) {
                            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                            handleSucess();

                        } else {
                            Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
                        }
                    }

                }
            }
        }
    }

    private void getOrder() {
        //得到店铺的Id
        SharedPreferences preferences = getSharedPreferences("StoreMessage", Context.MODE_PRIVATE);

        String Shopid = preferences.getString("Id", "");//得到店铺的ID
        preferences = getSharedPreferences("Token", Context.MODE_PRIVATE);
        String value = preferences.getString("value", "");
        String[] names = value.split("\\,");
        String deviceNo = names[2];//收银机号
        String uid = names[1];
        String cashierNumber = App.getCashierMsgDto().getNumber();
        String sid = GetData.getYYMMDDHHMMSSNoSpellingTime() + GetData.getStringRandom(20);//得到一个32位的随机数
        goodsInfo = getSharedPreferences("goodsdto_json", MODE_PRIVATE).getString("json", null);
        orderBeen = new OrderBeen();
        orderBeen.setSid(sid);
        orderBeen.setOrderNo(OrderNoUtil.getNumber());
        orderBeen.setAmount(je);
        orderBeen.setCashierNo(cashierNumber);
        orderBeen.setDate(GetData.getDataTime());
        orderBeen.setDeviceNo(deviceNo);
        orderBeen.setDiscount("0");
        orderBeen.setGoodsDetail(goodsInfo);
        orderBeen.setPayDetail(new Gson().toJson(payBeen, PayBeen.class));
        orderBeen.setShopNo(Shopid);
        orderBeen.setUid(uid);
        orderBeen.setStutas(UploadData.UP_FAILED);
        orderBeen.setSaveDate(GetData.getYYMMDD());
        orderBeen.setSaveTiem(GetData.getSearchTime());
        orderBeen.setPayId(unionId);//退款所需标识
        orderBeen.setOrderType("1");//销售
    }

    private void initCheck(View view) {
        for (ImageView img : payImg) {
            if (view == img) {
                img.setVisibility(View.VISIBLE);
            } else {
                img.setVisibility(View.INVISIBLE);
            }
        }
        setSs();

    }
    private void upOrder(){
        App.getInstance().getDaoSession().getOrderBeenDao().insert(orderBeen);
        RequestParams params = UploadData.getUpData(this, orderBeen);
        Log.i("up", params.toString());
        Log.i("up", Api.SYNCORDER);
        LoadServer.getConnect(this, Api.SYNCORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.d("value", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("Result").equals("1")) {
                        Message message = Message.obtain();
                        message.what = PayUtil.UPSUCCESS;
                        handler.sendMessage(message);
                        orderBeen.setStutas(UploadData.UP_SUCCESS);
                        App.getInstance().getDaoSession().getOrderBeenDao().update(orderBeen);
                    } else {
                        Message message = Message.obtain();
                        message.what = PayUtil.UPFAILED;
                        message.obj = object.getString("Message");
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = PayUtil.UPFAILED;
                    message.obj = "支付失败";
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = PayUtil.UPFAILED;
                message.obj = "网络异常";
                handler.sendMessage(message);
            }
        });
    }
    private void paySuccess(){

        Intent intent = new Intent(this, PaySuccessActivity.class);
        intent.putExtra(PUT_PAYWAY, payWayString);
        intent.putExtra(PUT_YS, je);
        intent.putExtra(PUT_ZL, "0");
        intent.putExtra(PUT_SS, je);
        intent.putExtra(PUT_MAXNO, String.valueOf(orderNo));
        intent.putExtra("remark", remark);
        startActivity(intent);
        finish();
    }
    private LoadingDialog loadingDialog;
    private void showLoading(String msg){
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
            loadingDialog.setMessage(msg);
            loadingDialog.show();
        }
    }
    private void closeLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

}
